package com.cgtong.android.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.support.annotation.IdRes;
import android.support.v7.widget.AppCompatCheckBox;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cgtong.android.App;
import com.cgtong.android.R;
import com.cgtong.android.base.BaseTitleActivity;
import com.cgtong.android.bean.ActivityDetailBean;
import com.cgtong.android.bean.ActivityVote;
import com.cgtong.android.http.ConstantManager;
import com.cgtong.android.mvp.contract.ActivityDetailContract;
import com.cgtong.android.mvp.presenter.ActivityDetailPresenter;
import com.cgtong.android.util.PostUtil;
import com.kingja.loadsir.callback.SuccessCallback;
import com.zhouyou.http.exception.ApiException;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Sky.Bing on 2017/10/23.
 */

public class ActivitiesDetailActivity extends BaseTitleActivity implements ActivityDetailContract.View {
    @BindView(R.id.tv_activity_title)
    public TextView mTvActivityTitle;
    @BindView(R.id.tv_activity_info)
    public TextView mTvActivityInfo;
    @BindView(R.id.tv_activity_choose_title)
    public TextView mTvActivityChooseTitle;
    @BindView(R.id.tv_activity_choose_type)
    public TextView mTvActivityChooseType;
    @BindView(R.id.rg_activity_choose)
    public RadioGroup mRgActivityChoose;
    @BindView(R.id.ll_chkbox_activity_choose)
    public LinearLayout mLlChkBoxActivityChoose;
    @BindView(R.id.btn_activity_vote)
    public Button mBtnActivityVote;

    private static final String EXTRA_ACTIVITY_ID = "extra_activity_id";
    private List<String> voteItems;
    private int mActivityId;
    private boolean isVoted;
    private int mActivityState;
    private List<CompoundButton> activityChooseList = new ArrayList<>();
    private ActivityDetailPresenter mActivityDetailPresenter;

    @Override
    protected String getContentTitle() {
        return getResources().getString(R.string.title_wonderful_activities);
    }

    public static void actionStart(Activity context, int activityId) {
        if (App.getInstance().isUserLogin()) {
            Intent intent = new Intent(context, ActivitiesDetailActivity.class);
            intent.putExtra(EXTRA_ACTIVITY_ID, activityId);
            context.startActivity(intent);
        } else {
            Intent itent = new Intent(context, LoginActivity.class);
            context.startActivityForResult(itent, ConstantManager.REQUEST_LOGIN_CODE);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_activites_detail;
    }

    @Override
    protected void loadDataByNet() {
        mBtnActivityVote.setEnabled(true);
        Intent intent = getIntent();
        mActivityId = intent.getIntExtra(EXTRA_ACTIVITY_ID, 0);
        if (mActivityId > 0) {
            mActivityDetailPresenter = new ActivityDetailPresenter(this);
            mActivityDetailPresenter.getActivityDetail(mActivityId);
        }
    }

    @Override
    protected void onDataReloadByNet(View v) {
    }

    @Override
    public void showDetail(ActivityDetailBean activityDetailBean) {
        mTvActivityTitle.setText(activityDetailBean.getTitle());
        mTvActivityInfo.setText(activityDetailBean.getContent());
        if (activityDetailBean.getType() == 1) {
            initRadioGroup(activityDetailBean.getVoteItems());
        } else if (activityDetailBean.getType() == 2) {
            initCheckBoxGroup(activityDetailBean.getVoteItems());
        } else { //其他值
            initRadioGroup(activityDetailBean.getVoteItems());
        }
        if (isVoted) {
            mBtnActivityVote.setEnabled(false);
        }
        //1正在进行 2未开始  3已过期  0未知
        mActivityState = activityDetailBean.getActivityState();
        if (mActivityState != 1) {
            if (activityChooseList.size() > 0) {
                for (CompoundButton compoundButton : activityChooseList) {
                    compoundButton.setClickable(false);
                    compoundButton.setFocusable(false);
                    compoundButton.setFocusableInTouchMode(false);
                }
            }
        }
        PostUtil.postCallbackDelayed(loadService, SuccessCallback.class);
    }

    private void initCheckBoxGroup(List<ActivityVote> activityVoteList) {
        mTvActivityChooseType.setText(R.string.txt_activity_vote_double);
        mRgActivityChoose.setVisibility(View.GONE);
        mLlChkBoxActivityChoose.setVisibility(View.VISIBLE);
        voteItems = new ArrayList<>();
        LayoutInflater inflater = LayoutInflater.from(this);
        for (ActivityVote vote : activityVoteList) {
            CompoundButton checkBox = (CheckBox) inflater.inflate(R.layout.checkbox_button_layout, (ViewGroup) this.getWindow().getDecorView(), false);
            if (vote.isVote()) {
                isVoted = true;
                checkBox.setChecked(true);
            }
            checkBox.setText(vote.getTitle());
            checkBox.setTag(vote.getId());
            checkBox.setTextColor(getResources().getColor(R.color.color_txt_activity_detail_vote_item));
            checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    String tag = String.valueOf(buttonView.getTag());
                    if (isChecked)
                        voteItems.add(tag);
                    else
                        voteItems.remove(tag);

                }
            });
            activityChooseList.add(checkBox);
            mLlChkBoxActivityChoose.addView(checkBox);
        }
        onSetActivityChoose();
    }

    private void initRadioGroup(List<ActivityVote> activityVoteList) {
        mTvActivityChooseType.setText(R.string.txt_activity_vote_single);
        mRgActivityChoose.setVisibility(View.VISIBLE);
        mLlChkBoxActivityChoose.setVisibility(View.GONE);
        voteItems = new ArrayList<>();
        Resources res = getResources();
        LayoutInflater inflater = LayoutInflater.from(this);
        for (ActivityVote vote : activityVoteList) {
            CompoundButton radioButton = (RadioButton) inflater.inflate(R.layout.radio_button_layout, (ViewGroup) this.getWindow().getDecorView(), false);
            if (vote.isVote()) {
                isVoted = true;
                radioButton.setChecked(true);
            }
            //radioButton.setBackgroundDrawable(null);
            //radioButton.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            //radioButton.setButtonDrawable(res.getDrawable(R.drawable.bg_radio_activity_vote));
            radioButton.setText(vote.getTitle());
            radioButton.setTag(vote.getId());
            radioButton.setTextColor(getResources().getColor(R.color.color_txt_activity_detail_vote_item));
            activityChooseList.add(radioButton);
            mRgActivityChoose.addView(radioButton);
        }
        mRgActivityChoose.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                voteItems.clear();
                RadioButton radioButton = (RadioButton) findViewById(checkedId);
                voteItems.add(String.valueOf(radioButton.getTag()));
            }
        });
        onSetActivityChoose();
    }

    private void onSetActivityChoose() {
        if (isVoted) {
            if (activityChooseList.size() > 0) {
                for (CompoundButton compoundButton : activityChooseList) {
                    compoundButton.setClickable(false);
                    compoundButton.setFocusable(false);
                    compoundButton.setFocusableInTouchMode(false);
                }
            }
        }
    }

    @OnClick(R.id.btn_activity_vote)
    public void doActivityVote() {
        if (mActivityState != 1) {
            switch (mActivityState) {  //1正在进行 2未开始  3已过期  0未知
                case 2:
                    ToastUtils.showShort("活动未开始");
                    return;
                case 0:
                case 3:
                    ToastUtils.showShort("活动已结束");
                    return;
            }
        }

        StringBuffer stringBuffer = new StringBuffer();
        if (null != voteItems && voteItems.size() > 0) {
            for (String str : voteItems) {
                stringBuffer.append(str + ",");
            }
        }
        String voteItems = stringBuffer.toString();
        if (!StringUtils.isTrimEmpty(voteItems)) {
            mActivityDetailPresenter.postActivityVote(mActivityId, voteItems.substring(0, voteItems.length() - 1));
        } else {
            ToastUtils.showLong(R.string.txt_activity_vote_choice);
        }
    }

    @Override
    public void postActivityVoteError(ApiException e) {
        if (e.getCode() == -1001) { //用户未登录
            Intent intent = new Intent(ActivitiesDetailActivity.this, LoginActivity.class);
            startActivityForResult(intent, ConstantManager.REQUEST_LOGIN_CODE);
        } else {
            if (TextUtils.isEmpty(e.getMessage())) {
                ToastUtils.showLong(e.getMessage());
            } else {
                ToastUtils.showLong(R.string.txt_activity_vote_error);
            }
        }
    }

    @Override
    public void postActivityVoteSuccess() {
        ToastUtils.showLong(R.string.txt_activity_vote_success);
        //投票成功无法继续投票
        isVoted = true;
        mBtnActivityVote.setEnabled(false);
        if (null != voteItems && voteItems.size() > 0 && activityChooseList.size() > 0) {
            for (CompoundButton compoundButton : activityChooseList) {
                if (voteItems.contains(String.valueOf(compoundButton.getTag()))) {
                    compoundButton.setChecked(true);
                } else {
                    compoundButton.setChecked(false);
                }
                compoundButton.setClickable(false);
                compoundButton.setFocusable(false);
                compoundButton.setFocusableInTouchMode(false);
            }
        }
    }

    @Override
    public void getDetailError(ApiException e) {
        PostUtil.postCallbackDelayed(loadService, SuccessCallback.class);
        if (e.getCode() == -1001) { //用户未登录
            Intent intent = new Intent(ActivitiesDetailActivity.this, LoginActivity.class);
            startActivityForResult(intent, ConstantManager.REQUEST_LOGIN_CODE);
        } else {
            if (!TextUtils.isEmpty(e.getMessage())) {
                ToastUtils.showLong(e.getMessage());
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ConstantManager.REQUEST_LOGIN_CODE) {
            if (resultCode == RESULT_OK) {
                mBtnActivityVote.setEnabled(true);
                mActivityDetailPresenter.getActivityDetail(mActivityId);
            } else {
                finish();
            }
        }
    }
}